/*
 * Copyright (c) 2011 Ball State University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * NOTE:
 * Derivative work based on the Google IO 2011 Schedule app released for open source
 * http://code.google.com/p/iosched/
 */

package edu.bsu.android.gtv.apps.bconnected.ui;

import java.util.ArrayList;

import edu.bsu.android.gtv.apps.bconnected.R;
import edu.bsu.android.gtv.apps.bconnected.data.MonthData;
import edu.bsu.android.gtv.apps.bconnected.objects.Month;
import edu.bsu.android.gtv.apps.bconnected.util.AnalyticsUtils;
import edu.bsu.android.gtv.apps.bconnected.util.PersistentListFragment;
import edu.bsu.android.gtv.apps.bconnected.util.UIUtils;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

/**
 * A simple {@link PersistentListFragment} that renders a list of months.  The listfragment appears in the left hand column of the 
 * {@link EventMultiPaneActivity} and when an item is selected, a list of events appears using the {@link EventFragment} in the 
 * right hand column.
 * @author Kyle Parker, University Computing Services
 */
public class MonthFragment extends PersistentListFragment {
    private static final String TAG = "MonthFragment";
	
    private Bundle mBundle = null;
	private OnMonthListener mMonthListener = null;
    private MonthAdapter mAdapter;
    private ArrayList<Month> mMonths;
    private Activity mActivity;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        
        mActivity = getActivity();
		this.mBundle = savedInstanceState;
        
        AnalyticsUtils.getInstance(mActivity).trackPageView("/Months");

		loadMonths();
        
        // Set the list style
    	Drawable selector = mActivity.getResources().getDrawable(R.drawable.list_selector_background_default);
    	getListView().setBackgroundDrawable(selector);
        setListShown(false);
		
		if (mMonthListener != null) {
			mMonthListener.onMonthSelected(0);
			getListView().setItemChecked(0, true);
		}
    }
	
	@Override
	public void onResume() {
		super.onResume();
		
		restoreState(mBundle);
	}

    /** {@inheritDoc} */
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		
		if (mMonthListener != null) {
			mMonthListener.onMonthSelected(position);
		}
    }

    /**
     * Using a new thread, separate from the main activity, load the months from the service handler
     */
    private void loadMonths() {
        mMonths = new ArrayList<Month>();
        mAdapter = new MonthAdapter(mActivity, R.layout.list_item, mMonths);
        setListAdapter(this.mAdapter);

        Runnable load = new Runnable(){
            public void run() {
            	try {
	                MonthData.initializeMonth();
	    	    	
	                mMonths = MonthData.getMonths();
	                
	            	mActivity.runOnUiThread(returnMonth);
            	} catch (Exception ex) {
                    AnalyticsUtils.getInstance(mActivity).trackPageView(TAG + ": " + ex.getMessage());
            	}
            }
        };
        
        Thread thread =  new Thread(null, load, "loadMonths");
        thread.start();      
    }
    
    /**
     * Add each month object from the service handler to the array adapter and set the visibility of the spinner to "gone"
     */
    private Runnable returnMonth = new Runnable(){
        public void run() {
            if (mMonths != null && mMonths.size() > 0){
                for(int i = 0; i < mMonths.size(); i++)
                {
                	mAdapter.add(mMonths.get(i));
                }
            }

            mAdapter.notifyDataSetChanged();
            setListShown(true);
            getListView().setFocusable(true);
            getListView().requestFocus();
        }
    };
    
    /**
     * MonthAdapter used to populate the listview for the months
     */
    private class MonthAdapter extends ArrayAdapter<Month> {
        private ArrayList<Month> items;
        
        public MonthAdapter(Context context, int textViewResourceId, ArrayList<Month> items) {
            super(context, textViewResourceId, items);
            this.items = items; 
        }
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent)  {                  	
            View view = convertView;
            
            if (view == null) {
            	view = LayoutInflater.from(mActivity).inflate(R.layout.list_item, null);
            }

            Month month = items.get(position);    
            
            if (month != null) {
            	UIUtils.displayTextView(view, R.id.item, month.getMonthWithYear());
            }
            
            return view;
        } 
    }
    
	public void setOnMonthListener(OnMonthListener listener) {
		this.mMonthListener = listener;
	}
	
	public interface OnMonthListener {
		void onMonthSelected(int position);
	}
}
